package org.oos.dao.options;

import java.util.Map;

import org.oos.atom.elements.Area;
import org.oos.atom.elements.GeoLocation;
import org.oos.dao.options.OptionsMap.OptionsFinder;
import org.oos.model.BBox;

import com.google.api.client.util.Key;

/**
 * Defines the limits of the search by a given location. If details that are
 * contradictory are set the result will not provide with any results.
 * 
 * @author pablo.gonzalez@11870.com
 * 
 */
@SuppressWarnings("unused")
public class LocationOptions extends OptionsMap {

	/* Filter by position */
	@Key("l")
	private String location;
	@Key
	private String bbox;

	@Key("lat")
	private String latitude;

	@Key("lon")
	private String longitude;

	@Key
	private String radius;

	@Key("as")
	private String area;

	private Float rawLatitude;
	private Float rawLongitude;
	private Float rawRadius;

	public void setGeoLocation(GeoLocation geoLocation) {
		if (geoLocation != null) {
			setLatitude(geoLocation.getLatitude());
			setLongitude(geoLocation.getLongitude());
			setRadius(geoLocation.getRadius());
		}
	}

	/**
	 * 
	 * Checks if the new double is a correct candidate for the oldDouble.
	 * 
	 * @param newDouble
	 * @param oldDouble
	 * @return
	 */
	private boolean valid(Float newDouble, Float oldDouble) {
		return newDouble != null
				&& (oldDouble == null || !oldDouble.equals(newDouble));
	}

	private void setLatitude(Float latitude) {
		if (valid(latitude, rawLatitude)) {
			rawLatitude = latitude;
			this.latitude = latitude.toString();
		}
	}

	private void setLongitude(Float longitude) {
		if (valid(longitude, rawLongitude)) {
			rawLongitude = longitude;
			this.longitude = longitude.toString();
		}
	}

	private void setRadius(Float radius) {
		if (valid(radius, rawRadius)) {
			rawRadius = radius;
			this.radius = radius.toString();
		}
	}

	public void setArea(Area area) {
		this.area = area.getSlug();
	}

	public void setLocation(String location) {
		this.location = location;
	}

	public void setBbox(BBox bbox) {
		if (bbox != null)
			this.bbox = bbox.toString();
	}

	@Override
	public Map<String, Object> toMap() {
		Map<String, Object> results = super.toMap();

		return results;
	}

	public void clear() {
		location = bbox = latitude = longitude = radius = area = null;
	}

}
